package com.daikit.daikit4gxt.shared.bean;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;


/**
 * Wrapper for RPC returned value when return type is abstract
 *
 * @author tcaselli
 * @version $Revision$ Last modifier: $Author$ Last commit: $Date$
 * @param <TYPE>
 */
public class DkDataWrapper<TYPE extends Serializable> implements Serializable
{

	private static final long serialVersionUID = 8295585335292650739L;

	// That's a way to have its serialization allowed
	protected List<TYPE> values = new ArrayList<TYPE>();

	/**
	 * Constructor
	 */
	public DkDataWrapper()
	{
		// Nothing done
	}

	/**
	 * Constructor
	 *
	 * @param value
	 *           the wrapped value
	 */
	public DkDataWrapper(final TYPE value)
	{
		this.values.add(value);
	}

	/**
	 * @return the value
	 */
	public TYPE getValue()
	{
		return values.isEmpty() ? null : values.get(0);
	}

	/**
	 * @param value
	 *           the value to set
	 */
	public void setValue(final TYPE value)
	{
		values.clear();
		values.add(value);
	}


	/**
	 * Convert a list of model to the corresponding {@link DkDataWrapper} list
	 *
	 * @param list
	 * @return the corresponding {@link DkDataWrapper} list
	 */
	public static <M extends Serializable> List<DkDataWrapper<M>> convert(final List<M> list)
	{
		final List<DkDataWrapper<M>> ret = new ArrayList<DkDataWrapper<M>>();
		for (final M value : list)
		{
			ret.add(new DkDataWrapper<M>(value));
		}
		return ret;
	}

	/**
	 * Convert a list of {@link DkDataWrapper} to the corresponding list of values
	 *
	 * @param list
	 * @return the corresponding value list
	 */
	public static <M extends Serializable> List<M> convertBack(final List<DkDataWrapper<M>> list)
	{
		final List<M> ret = new ArrayList<M>();
		for (final DkDataWrapper<M> valueWrapper : list)
		{
			ret.add(valueWrapper.getValue());
		}
		return ret;
	}

}
